#!/usr/bin/env python
# encoding: utf-8
# 访问 http://tool.lu/pyc/ 查看更多信息
'''
Created on 2016-04-28
@author: fan
'''

import time, sys, os
import logging
import logging.handlers
from logging import getLogger, INFO, WARN, DEBUG, ERROR, FATAL, WARNING, CRITICAL


class Log(object):
    LOG_FILE_MAXBYTES = 1024*1024
    LOG_FILE_BACKUPCOUNT = 1000
    LOG_LEVEL = None
    LOG_FILENAME = None
    normalHandler = None

    def __init__(self, logname):
        now = time.strftime('%Y%m%d', time.localtime(time.time()))
        DIRNAME = 'logs/' + now
        self.checkDir(DIRNAME)
        self.initlog(DIRNAME)
        normalLog = getLogger(logname)
        normalLog.setLevel(self.LOG_LEVEL)
        normalLog.addHandler(self.normalHandler)
        self.normalLog = normalLog

    def checkDir(self, DIRNAME):
        if not os.path.exists(DIRNAME):
            os.makedirs(DIRNAME)

    def initlog(self, DIRNAME):
        self.LOG_LEVEL = logging.DEBUG
        self.LOG_FILENAME = DIRNAME + '/kafka_debug.log'
        FORMAT = '[%(asctime)s]-%(levelname)-8s<%(name)s>{%(filename)s:%(lineno)s} -> %(message)s'
        formatter = logging.Formatter(FORMAT)
        self.normalHandler = logging.handlers.RotatingFileHandler(self.LOG_FILENAME, maxBytes=self.LOG_FILE_MAXBYTES,
                                                                  backupCount=self.LOG_FILE_BACKUPCOUNT)
        self.normalHandler.setFormatter(formatter)

    def setLevel(self, level):
        self.normalLog.setLevel(level)

    def debug(self, msg, *args, **kwargs):
        if self.normalLog.isEnabledFor(DEBUG):
            self.normalLog._log(DEBUG, msg, args, **kwargs)


    def info(self, msg, *args, **kwargs):
        if self.normalLog.isEnabledFor(INFO):
            self.normalLog._log(INFO, msg, args, **kwargs)


    def warning(self, msg, *args, **kwargs):
        if self.normalLog.isEnabledFor(WARN):
            self.normalLog._log(WARNING, msg, args, **kwargs)

    def warn(self, msg, *args, **kwargs):
        if self.normalLog.isEnabledFor(WARN):
            self.normalLog._log(WARN, msg, args, **kwargs)

    def error(self, msg, *args, **kwargs):
        if self.errorLog.isEnabledFor(ERROR):
            self.normalLog._log(ERROR, msg, args, **kwargs)
            self.errorLog._log(ERROR, msg, args, **kwargs)

    def critical(self, msg, *args, **kwargs):
        if self.errorLog.isEnabledFor(CRITICAL):
            self.normalLog._log(CRITICAL, msg, args, **kwargs)

    def fatal(self, msg, *args, **kwargs):
        if self.errorLog.isEnabledFor(FATAL):
            self.normalLog._log(FATAL, msg, args, **kwargs)


